// 商城页面交互功能

document.addEventListener('DOMContentLoaded', function() {
    // 设置分类筛选
    setupCategoryFilter();
    
    // 设置搜索功能
    setupSearch();
    
    // 设置产品卡片交互
    setupProductCards();
    
    // 设置收藏功能
    setupWishlist();
    
    // 设置购物车功能
    setupCart();
    
    // 设置底部导航
    setupBottomNavigation();
});

// 分类筛选功能
function setupCategoryFilter() {
    const categoryBtns = document.querySelectorAll('.category-btn');
    
    categoryBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            // 移除所有活动状态
            categoryBtns.forEach(b => b.classList.remove('active'));
            
            // 设置当前按钮为活动状态
            this.classList.add('active');
            
            // 添加点击动画
            this.style.transform = 'scale(0.95)';
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 150);
            
            // 筛选产品
            const category = this.textContent;
            filterProducts(category);
        });
    });
}

// 筛选产品
function filterProducts(category) {
    const productCards = document.querySelectorAll('.product-card');
    
    productCards.forEach((card, index) => {
        if (category === '全部') {
            card.style.display = 'block';
            card.style.animation = `fadeInUp 0.6s ease-out ${index * 0.1}s both`;
        } else {
            // 这里可以根据实际的产品分类进行筛选
            // 现在只是简单的随机显示/隐藏
            const shouldShow = Math.random() > 0.3;
            if (shouldShow) {
                card.style.display = 'block';
                card.style.animation = `fadeInUp 0.6s ease-out ${index * 0.1}s both`;
            } else {
                card.style.display = 'none';
            }
        }
    });
}

// 搜索功能
function setupSearch() {
    const searchInput = document.querySelector('input[type="text"]');
    const searchIcon = document.querySelector('.fa-search');
    
    let searchTimeout;
    
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        const query = this.value.toLowerCase();
        
        searchTimeout = setTimeout(() => {
            if (query.length > 0) {
                searchProducts(query);
            } else {
                resetSearch();
            }
        }, 300);
    });
    
    searchInput.addEventListener('focus', function() {
        this.parentElement.style.transform = 'scale(1.02)';
    });
    
    searchInput.addEventListener('blur', function() {
        this.parentElement.style.transform = 'scale(1)';
    });
    
    searchIcon.addEventListener('click', function() {
        searchInput.focus();
    });
}

// 搜索产品
function searchProducts(query) {
    const productCards = document.querySelectorAll('.product-card');
    
    productCards.forEach(card => {
        const productName = card.querySelector('h3').textContent.toLowerCase();
        const productDesc = card.querySelector('p').textContent.toLowerCase();
        
        if (productName.includes(query) || productDesc.includes(query)) {
            card.style.display = 'block';
            card.style.animation = 'fadeInUp 0.6s ease-out';
        } else {
            card.style.display = 'none';
        }
    });
}

// 重置搜索
function resetSearch() {
    const productCards = document.querySelectorAll('.product-card');
    
    productCards.forEach((card, index) => {
        card.style.display = 'block';
        card.style.animation = `fadeInUp 0.6s ease-out ${index * 0.1}s both`;
    });
}

// 产品卡片交互
function setupProductCards() {
    const productCards = document.querySelectorAll('.product-card');
    
    productCards.forEach(card => {
        // 点击事件
        card.addEventListener('click', function(e) {
            // 如果点击的是收藏按钮，不触发卡片点击
            if (e.target.closest('.wishlist-btn')) return;
            
            // 添加点击动画
            this.style.transform = 'scale(0.98)';
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 150);
            
            // 显示产品详情
            const productName = this.querySelector('h3').textContent;
            showProductDetail(productName);
        });
        
        // 3D预览按钮
        const badge3D = card.querySelector('[class*="3d-badge"]');
        if (badge3D) {
            badge3D.addEventListener('click', function(e) {
                e.stopPropagation();
                const productName = card.querySelector('h3').textContent;
                show3DPreview(productName);
            });
        }
    });
}

// 显示产品详情
function showProductDetail(productName) {
    console.log(`显示产品详情: ${productName}`);
    // 这里可以添加跳转到产品详情页的逻辑
    // window.location.href = `product.html?name=${encodeURIComponent(productName)}`;
}

// 显示3D预览
function show3DPreview(productName) {
    console.log(`显示3D预览: ${productName}`);
    // 这里可以添加3D预览的逻辑
    alert(`正在加载 ${productName} 的3D模型...`);
}

// 收藏功能
function setupWishlist() {
    const wishlistBtns = document.querySelectorAll('.wishlist-btn');
    
    wishlistBtns.forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            
            const icon = this.querySelector('i');
            const isActive = this.classList.contains('active');
            
            if (isActive) {
                // 取消收藏
                this.classList.remove('active');
                icon.classList.remove('fas');
                icon.classList.add('far');
                icon.style.color = '#9ca3af';
                showToast('已取消收藏');
            } else {
                // 添加收藏
                this.classList.add('active');
                icon.classList.remove('far');
                icon.classList.add('fas');
                icon.style.color = '#ef4444';
                showToast('已添加到收藏');
                
                // 添加心形动画
                createHeartAnimation(this);
            }
            
            // 添加点击动画
            this.style.transform = 'scale(1.2)';
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 200);
        });
    });
}

// 创建心形动画
function createHeartAnimation(button) {
    const heart = document.createElement('div');
    heart.innerHTML = '❤️';
    heart.style.position = 'absolute';
    heart.style.fontSize = '20px';
    heart.style.animation = 'heartFloat 1s ease-out forwards';
    heart.style.pointerEvents = 'none';
    heart.style.zIndex = '1000';
    
    const rect = button.getBoundingClientRect();
    heart.style.left = rect.left + rect.width / 2 + 'px';
    heart.style.top = rect.top + 'px';
    
    document.body.appendChild(heart);
    
    setTimeout(() => {
        heart.remove();
    }, 1000);
}

// 购物车功能
function setupCart() {
    const cartBtn = document.querySelector('.fa-shopping-cart').parentElement;
    const cartBadge = cartBtn.querySelector('span');
    
    cartBtn.addEventListener('click', function() {
        showToast('购物车功能开发中...');
    });
    
    // 为每个产品卡片添加添加到购物车的功能
    const productCards = document.querySelectorAll('.product-card');
    
    productCards.forEach(card => {
        // 双击添加到购物车
        card.addEventListener('dblclick', function() {
            addToCart(this);
        });
    });
}

// 添加到购物车
function addToCart(productCard) {
    const cartBadge = document.querySelector('.fa-shopping-cart').parentElement.querySelector('span');
    const currentCount = parseInt(cartBadge.textContent);
    
    cartBadge.textContent = currentCount + 1;
    
    // 添加动画
    cartBadge.style.animation = 'bounce 0.6s ease-out';
    setTimeout(() => {
        cartBadge.style.animation = '';
    }, 600);
    
    const productName = productCard.querySelector('h3').textContent;
    showToast(`已添加 ${productName} 到购物车`);
    
    // 添加飞入动画
    createFlyAnimation(productCard, cartBadge);
}

// 创建飞入动画
function createFlyAnimation(productCard, targetElement) {
    const flyElement = document.createElement('div');
    flyElement.style.position = 'fixed';
    flyElement.style.width = '20px';
    flyElement.style.height = '20px';
    flyElement.style.background = '#ef4444';
    flyElement.style.borderRadius = '50%';
    flyElement.style.zIndex = '1000';
    
    const startRect = productCard.getBoundingClientRect();
    const targetRect = targetElement.getBoundingClientRect();
    
    flyElement.style.left = startRect.left + startRect.width / 2 + 'px';
    flyElement.style.top = startRect.top + startRect.height / 2 + 'px';
    
    document.body.appendChild(flyElement);
    
    // 飞行动画
    flyElement.animate([
        { transform: 'translate(0, 0) scale(1)', opacity: 1 },
        { transform: `translate(${targetRect.left - startRect.left}px, ${targetRect.top - startRect.top}px) scale(0.5)`, opacity: 0 }
    ], {
        duration: 800,
        easing: 'ease-out'
    }).onfinish = () => {
        flyElement.remove();
    };
}

// 显示提示
function showToast(message) {
    const toast = document.createElement('div');
    toast.textContent = message;
    toast.style.position = 'fixed';
    toast.style.bottom = '100px';
    toast.style.left = '50%';
    toast.style.transform = 'translateX(-50%)';
    toast.style.background = 'rgba(0,0,0,0.8)';
    toast.style.color = 'white';
    toast.style.padding = '12px 24px';
    toast.style.borderRadius = '24px';
    toast.style.fontSize = '14px';
    toast.style.zIndex = '1000';
    toast.style.animation = 'fadeInOut 2s ease-out forwards';
    
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, 2000);
}

// 底部导航
function setupBottomNavigation() {
    const navItems = document.querySelectorAll('.fixed.bottom-0 .text-center');
    
    navItems.forEach((item, index) => {
        item.addEventListener('click', function() {
            // 移除所有活动状态
            navItems.forEach(nav => {
                const icon = nav.querySelector('i');
                const text = nav.querySelector('p');
                icon.classList.remove('text-green-600');
                icon.classList.add('text-gray-400');
                text.classList.remove('text-green-600');
                text.classList.add('text-gray-400');
            });
            
            // 设置当前项为活动状态
            const currentIcon = this.querySelector('i');
            const currentText = this.querySelector('p');
            currentIcon.classList.remove('text-gray-400');
            currentIcon.classList.add('text-green-600');
            currentText.classList.remove('text-gray-400');
            currentText.classList.add('text-green-600');
        });
    });
}

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes heartFloat {
        0% {
            transform: translateY(0) scale(1);
            opacity: 1;
        }
        100% {
            transform: translateY(-50px) scale(1.5);
            opacity: 0;
        }
    }
    
    @keyframes fadeInOut {
        0% { opacity: 0; transform: translateX(-50%) translateY(20px); }
        20% { opacity: 1; transform: translateX(-50%) translateY(0); }
        80% { opacity: 1; transform: translateX(-50%) translateY(0); }
        100% { opacity: 0; transform: translateX(-50%) translateY(-20px); }
    }
`;
document.head.appendChild(style);